<template>
    <div class="boxContentCss">
        <el-form ref="formRef" :model="form" label-position="right" label-width="110px">
            <EdCreateCard title="新增">
                <template #back>
                    <div class="createBack" @click="utilsSet.goBack(router)" >
                        <svg-icon icon-class="back" /> 返回
                    </div>
                </template>
                <div class="zh_flex">
                    <el-row class="width-100">
                        <el-col :span="6">
                            <el-form-item label="房号" prop="roomNo" :rules="$validate.validates({required:true,msg:'不能为空',trigger:['blur','change']})">
                                <EdLazyCascader style="width:100%" ref="edLazyCascader" :houseRentParams="data.houseRentParams" placeholder="小区/分期/楼栋/单元/房间" leafLevel="4" @emit-cascader-value="emitCascaderValue"></EdLazyCascader>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="联系人" prop="leaserName" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-input class="flex-input"  placeholder="请输入联系人" v-model="form.leaserName"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="联系电话" prop="leaserPhone" :rules="$validate.validates({required:true,msg:'不能为空',type:'tel'})">
                                <el-input class="flex-input"  placeholder="请输入联系电话" v-model="form.leaserPhone"></el-input>
                            </el-form-item>
                        </el-col> 
                    </el-row>
                    <el-row class="width-100">
                        <el-col :span="6">
                            <el-form-item label="出租方式" prop="rentWay" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <template>
                                    <el-radio v-model="form.rentWay" label='1'>整租</el-radio>
                                    <el-radio v-model="form.rentWay" label='2'>合租</el-radio>
                                </template>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="房屋面积" prop="houseArea" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-input class="flex-input" placeholder="请输入" v-model="form.houseArea">
                                    <i slot="suffix" style="font-style:normal;margin-right: 10px;">㎡</i>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="9" style="display: flex;">
                            <el-form-item  label-width="55px" label="户型" prop="" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-input class="flex-input" placeholder="请输入" v-model="form.room" >
                                    <i slot="suffix" style="font-style:normal;margin-right: 10px;">室</i>
                                </el-input>
                            </el-form-item>
                            <el-form-item label-width="20px" prop="" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-input class="flex-input" placeholder="请输入" v-model="form.hall">
                                    <i slot="suffix" style="font-style:normal;margin-right: 10px;">厅</i>
                                </el-input>
                            </el-form-item>
                            <el-form-item   label-width="20px" prop="" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-input class="flex-input" placeholder="请输入" v-model="form.kitchen">
                                    <i slot="suffix" style="font-style:normal;margin-right: 10px;">厨</i>
                                </el-input>
                            </el-form-item>
                            <el-form-item   label-width="20px" prop="" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-input class="flex-input" placeholder="请输入" v-model="form.toilets">
                                    <i slot="suffix" style="font-style:normal;margin-right: 10px;">卫</i>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-100">
                        <el-col :span="6">
                            <el-form-item label="装修类型" prop="decorate" :rules="$validate.validates({required:true,msg:'不能为空',type: 'producetName'})">
                                <EdSelect v-model="form.decorate" :selectParams="data.selectRenovation"></EdSelect> 
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="租金" prop="rent" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-input class="flex-input" placeholder="请输入" v-model="form.rent">
                                    <i slot="suffix" style="font-style:normal;margin-right: 10px;">元/月</i>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-80">
                        <el-col :span="24">
                            <el-form-item label="图片" prop="pics" :rules="$validate.validates({required:true,msg:'不能为空'})">
                                <el-upload
                                    accept=".jpg, .jpeg, .png, .gif"
                                    :action="data.action"
                                    list-type="picture-card"
                                    :limit="5"
                                    :multiple="true"
                                    :file-list="data.fileList"
                                    :before-upload="beforeImgUpload"
                                    :on-preview="handleImgPreview"
                                    :on-success="handleImgSuccess"
                                    :on-remove="handleImgRemove">
                                    <i class="el-icon-plus"></i>
                                </el-upload>
                            <el-dialog :visible.sync="data.dialogVisible">
                                <img width="100%" :src="data.dialogImageUrl" alt="">
                            </el-dialog>
                            <p class="labelFont">请上传2M以内的图片，建议上传图片大小430px*430px,格式为jpeg、jpg、png、gif的图片，至多5张</p>
                        </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="width-80">
                        <el-col :span="24">
                            <el-form-item label="房屋简介" prop="description" >
                                <EdTinymce ref="EdTinymce" v-model="form.description"></EdTinymce>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <el-form-item class="form_btns">
                    <el-button class="ed-button ed_black-bottom" @click="onSubmit()" >确定</el-button>
                    <el-button class="ed-button ed_white_bottom" @click="utilsSet.goBack(router)">取消</el-button>
                </el-form-item>
            </EdCreateCard>
            <EdConfirmDelete ref="confirmDeleteRef" @confirmDeleteTrue="confirmDeleteTrue"></EdConfirmDelete>
        </el-form>
    </div>
</template>

<script setup>
    import EdTinymce from 'src/components/EdTinymce.vue'
    import EdCreateCard from 'src/components/EdCreateCard.vue'
    import EdSelect from 'src/components/EdSelect.vue'
    import * as utilsSet from "../../../utils/utilsSet"
    import EdLazyCascader from 'src/components/EdLazyCascader.vue'
    import { onActivated, reactive, onDeactivated,ref } from 'vue'
    import EdConfirmDelete from "src/components/EdConfirmDelete.vue";
    import * as api from "./api";
    import message from 'src/utils/once-message'
    import router from 'src/router'
    const form = reactive({
        roomNo: '',
        leaserName: '',
        leaserPhone: '',
        rentWay: '',
        houseArea: '',
        houseType: '',
        decorate: '',
        rent: '',
        pics: [],
        description: '',
    })
    const formRef = ref()
    const edLazyCascader = ref()
    // const EdTinymce = ref()
    const confirmDeleteRef = ref()
    const table = ref()

    const data = reactive({
        fileList: [],
        action: '',
        dialogImageUrl: '',
        dialogVisible: false,
        selectRenovation:{  // 装修类型
            placeholder:"请选择装修类型",
            options: [
                { value: '1', label: '毛坯' },
                { value: '2', label: '简装' },
                { value: '3', label: '中装' },
                { value: '4', label: '精装' },
            ]
        },
        houseRentParams:{
            options: [],
        },
        checkType:'',
        roomId:'',
        // 房屋新增时校验的参数
        checkTypeForm:{
            roomNo:'',
            leaserName:''
        }
    })
    onActivated(()=>{
        // data.action = this.$baseApi + "/infra/file/upload";
        data.action = import.meta.env.VITE_BASE_API + "/infra/file/upload";
        if(route.query.id && route.query.leaseStatus==1){
            // 编辑 
            houseRentInfo();
        }else {
            
        }
       getresidentsByRoomId()
    })
    onDeactivated(()=>{
        form={}
        data.fileList = [];
        formRef.value.resetFields()
        edLazyCascader.value.reset();
        // 清空editor的缓存
        if(EdTinymce) EdTinymce.$children[0].cache = '';
    })
    function houseRentInfo(){
        // 编辑回显的接口
        api.houseRentInfo({id:router.currentRoute.query.id}).then(response => {
            if(response.success == true) {
                form = {...response.data};
                form.pics = response.pics
                data.fileList = response.data.pics.map(v=>{
                    return {url: v}
                })
            }
        })
    }
    function onSubmit(){
        // 房屋租赁添加时候校验
            data.checkTypeForm.roomNo=roomId
            data.checkTypeForm.leaserName=form.leaserName
        api.checkContact(data.checkTypeForm).then(res=>{
            if(res.success){
                data.checkType = res.data.checkType
                // 匹配成功，不弹框
                if(data.checkType==1){
                        form.roomNo = data.roomId
                        api.houseRentAdd(form).then(res=>{
                            message.success({
                                message: '新增成功', 
                                center: true,
                                duration: 2000,
                            })
                            router.back()
                            utilsSet.goBack(router);
                            // this.$set(this.form, 'description', '')
                            formRef.value.resetFields()
                        })
                }else if(data.checkType==2){
                confirmDeleteRef.value.open('操作确认',"联系人信息与房间信息不匹配，是否继续发布？")
                }
            }
        })
    }
      // 匹配直接调接口
      function confirmDeleteTrue(){
            form.roomNo = data.roomId
            api.houseRentAdd(form).then(res=>{
                message.success({
                    message: '新增成功',
                    center: true,
                    duration: 2000,
                })
                table.value.load()
                // this.$set(this.form, 'description', '')
                formRef.value.resetFields()
            })
    }
     // 图片 上传前
     function beforeImgUpload(file){
        // console.log('before-->', file)
        const fileType = file.name.split('.');
        const fileDate = fileType.slice(-1);
        if (['jpeg', 'jpg', 'png', 'gif'].indexOf(fileDate[0]) < 0) {
            message.error('仅支持格式：.jpg、.png、.gif!');
            return false
        }
        const isLt5M = file.size / 1024 /1024 < 2;
        if (!isLt5M) {
            return message.error('上传文件大小不能超过 2MB!');
        }
        // return isLt5M;
        return true;
    }
     // 图片 上传成功
     function handleImgSuccess(response, file, fileList){
        let res = file.response;
        if(res&&res.success == true){
            form.pics.push(res['data'])
        }
    }
     // 图片 删除
     function handleImgRemove(file, fileList) {
        form.pics = fileList&&fileList.map(v=>{
            return v['url']
        })
    }
      // 图片 预览
      function handleImgPreview(file) {
        data.dialogImageUrl = file.url;
        fata.dialogVisible = true;
    }
    function  emitCascaderValue(data){
        let arr = [];
        arr.push(data&&data[data.length-1]);
        data.roomId = arr[0];
        if(data.length) getresidentsByRoomId();
    }
    function getresidentsByRoomId(){
        api.getresidentsByRoomId({roomId:data.roomId}).then(res => {
            if(res.success == true) {
                form.leaserName = res.data.residentName;
                form.leaserPhone = res.data.phone;
            }
        })
    }
</script>

<style scoped lang="scss">
    :deep {
        .el-form-item{
            .el-form-item__content{
                .el-input{
                    // width: 98% !important;
                    width: 100% !important;
                }
                .el-select{
                    width: 100% !important;
                    // width: 98% !important;
                    // .el-input{
                    //     width: 100% !important;
                    // }
                }
                 .el-cascader{
                    width: 100% !important;
                    // width: 98% !important;
                    // .el-input{
                    //     width: 100% !important;
                    // }
                }
                .el-date-editor{
                    width: 100% !important;
                    // width: 98% !important;
                }
                .el-radio-group .el-radio.is-checked{
                    .el-radio__input{
                        .el-radio__inner{
                            border-color: #EED096;
                            background: #EED096;
                        }
                    }
                    .el-radio__label{
                        color: #EED096;
                    }
                }

                .el-radio-group .el-radio{
                    .el-radio__input{
                        .el-radio__inner:hover{
                            border-color: #EED096;
                        }
                    }
                }
            }
        }
    }
    .img_center{
        display: flex;
        align-items: center;
    }
    .form_btns{
        // display: flex;
        // justify-content: flex-end;
        margin-left: 47px;
    }
    .labelFont{
        font-family: 'Noto Sans SC';
        font-style: normal;
        font-weight: 400;
        font-size: 14px;
        color: #989898;
    }
</style>